import React from 'react';
import {Spin, Card, Button, Row, Col, Form} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {FORM_OPTIONS, DATE_FORMAT} from '../constants';
import {PERMISSION} from './constants';
import {hasPermissions} from './utils';
import {injectIntl} from './intl';
import {conventEnumValueToString, formatDateTime} from '../utils';
import TextInput from 'Shared/components/TextInput';
import WrappedDatePicker from '../common/WrappedDatePicker';
import styles from './style.css';
import Return from '../common/Return';
import {shipmentValidator} from './validator';
import {declarePlace, declareType, transportType} from '../Enum';
import {getDetail} from './api';
import FileUpload from './FileUpload';

const EMPTY_ARRAY = [];
const FormItem = Form.Item;
class DeliveryPanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        data: {}
    }
    componentDidMount() {
        if(this.props.id) {
            this.setState({loading: true});
            getDetail(this.props.id)
                .then(res => {
                    if(res.ok)
                        this.setState({
                            loading: false,
                            data: res.data
                        });
                    else
                        this.setState(({
                            loading: false
                        }));
                });
        }
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    removeFilePath = file => {
        const data = this.state.data;
        const index = data.attachments.findIndex(item => item.fileId === file.fileId);
        if(index === -1)
            return null;
        const attachments = data.attachments || [];
        attachments.splice(index, 1);
        if(!this.state.hasOperat)
            this.setState({
                data: {
                    ...data,
                    attachments
                },
                hasOperat: true,
            });
    }
    onChangeUpload = value => {
        const data = this.state.data;
        const attachments = data.attachments || [];
        attachments.push(value[0]);
        if(!this.state.hasOperat)
            this.setState({
                data: {
                    ...data,
                    attachments
                },
                hasOperat: true,
            });
    }
    onChange = (value, name) => {
        if(name === 'shipmentDate')
            this.setState({
                data: Object.assign({}, this.state.data, {
                    [name]: value,
                    expectDepartedDate: value,
                    actualDepartedDate: value,
                }),
                hasOperat: true
            });
        else this.setState({
            data: Object.assign({}, this.state.data, {
                [name]: value
            }),
            hasOperat: true
        });
    }
    onClickOkOnPopconfirm = () => {
        this.props.onCancel();
    }
    onSubmit = () => {
        const {data} = this.state;
        const isValid = shipmentValidator(data);
        if(!isValid) {
            this.setState({
                validate: true
            });
            return;
        }
        this.setState({loading: true});
        this.props.onSubmit(data).then(res => {
            if(res.success)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {data, loading} = this.state;
        const validateExpectArrivalDate = !data.expectArrivalDate && this.state.validate ? 'error' : null;
        const validateShipmentDate = !data.shipmentDate && this.state.validate ? 'error' : null;
        const submitable = !hasPermissions(PERMISSION.shipment, this.props.permissions);
        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Card title={formatMessage({
                        id: 'shipmentPanel.column.common',
                        defaultMessage: '基础信息'
                    })}>
                        <Form>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'shipmentPanel.operation.code',
                                        defaultMessage: '编号'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                        {data.code}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'shipmentPanel.operation.partContractInvoiceCode',
                                        defaultMessage: '发票号'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                        {data.partContractInvoiceCode}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'shipmentPanel.operation.dealerCode',
                                        defaultMessage: '总代编号'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                        {data.dealerCode}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'shipmentPanel.operation.country',
                                        defaultMessage: '国家'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                        {data.country}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'shipmentPanel.operation.invoicedDate',
                                        defaultMessage: '开票日期'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                        {formatDateTime(data.invoicedDate, DATE_FORMAT)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'shipmentPanel.operation.shipmentType',
                                        defaultMessage: '运输方式'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(transportType, data.shipmentType)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'shipmentPanel.operation.origin',
                                        defaultMessage: '起运地'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                        {data.origin}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'shipmentPanel.operation.destination',
                                        defaultMessage: '目的地'
                                    })}
                                    {...FORM_OPTIONS.item}>
                                        {data.destination}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'shipmentPanel.operation.expectDepartedDate',
                                        defaultMessage: '预计离港日期'
                                    })} {...FORM_OPTIONS.item}>
                                        {formatDateTime(data.expectDepartedDate, DATE_FORMAT)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'shipmentPanel.operation.declarePlace',
                                        defaultMessage: '报关地点'
                                    })} {...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(declarePlace, data.declarePlace)}
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'shipmentPanel.operation.declareType',
                                        defaultMessage: '报关类型'
                                    })} {...FORM_OPTIONS.item}>
                                        {conventEnumValueToString(declareType, data.declareType)}
                                    </FormItem>
                                </Col>
                            </Row>
                        </Form>
                    </Card>
                    <Card title={formatMessage({
                        id: 'shipmentPanel.column.shipment',
                        defaultMessage: '发运信息'
                    })}>
                        <Form>
                            <Row>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'shipmentPanel.form.shipmentDate',
                                            defaultMessage: '出运日期'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={validateShipmentDate}
                                        required>
                                        <WrappedDatePicker
                                            name="shipmentDate"
                                            value={data.shipmentDate}
                                            onChange={this.onChange}/>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'shipmentPanel.form.actualDepartedDate',
                                            defaultMessage: '实际离港日期'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <WrappedDatePicker
                                            name="actualDepartedDate"
                                            value={data.actualDepartedDate}
                                            onChange={this.onChange}/>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'shipmentPanel.form.expectArrivalDate',
                                            defaultMessage: '预计到港日期'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={validateExpectArrivalDate}
                                        required>
                                        <WrappedDatePicker
                                            name="expectArrivalDate"
                                            value={data.expectArrivalDate}
                                            onChange={this.onChange}/>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'shipmentPanel.form.actualArrivalDate',
                                            defaultMessage: '实际到港日期'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <WrappedDatePicker
                                            name="actualArrivalDate"
                                            value={data.actualArrivalDate}
                                            onChange={this.onChange}/>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'shipmentPanel.operation.shipmentNumber',
                                        defaultMessage: '运输单据号'
                                    })} {...FORM_OPTIONS.item}>
                                        <TextInput
                                            name="shipmentNumber"
                                            value={data.shipmentNumber}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={formatMessage({
                                        id: 'shipmentPanel.operation.shippingCompanyAirline',
                                        defaultMessage: '船公司/航空公司'
                                    })} {...FORM_OPTIONS.item}>
                                        <TextInput
                                            name="shippingCompanyAirline"
                                            value={data.shippingCompanyAirline}
                                            onBlur={this.onChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                        </Form>
                    </Card>
                    <Card title={formatMessage({
                        id: 'shipmentPanel.title.files',
                        defaultMessage: '附件清单'
                    })}>
                        <Row>
                            <Col {...FORM_OPTIONS.col}>
                                <FileUpload onChange={this.onChangeUpload}
                                    onRemove={this.removeFilePath}
                                    fileList={data.attachments || EMPTY_ARRAY}/>
                            </Col>
                        </Row>
                    </Card>
                    <Card className={styles.optionBtn}>
                        <Button
                            type="primary"
                            onClick={this.onSubmit}
                            disabled={!submitable}
                            loading={loading}>
                            {formatMessage({
                                id: 'shipmentPanel.operation.onSave',
                                defaultMessage: '保存'
                            })}
                        </Button>
                    </Card>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        onConfirm={this.onClickOkOnPopconfirm}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

DeliveryPanel.propTypes = {
    permissions: PropTypes.array.isRequired,
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    history: PropTypes.object,
    id: PropTypes.string,
    intl: PropTypes.object,
};

import {connect} from 'react-redux';
import {
    tableSearch,
    onShipment
} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = (state, props) => ({
    permissions: getPermissions(state),
});
const mapDispatchToProps = (dispatch, props) => ({
    onSubmit: data => dispatch(onShipment(data)),
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(DeliveryPanel));
